using System.Collections.Generic;
using Microsoft.Samples.ServiceHosting.StorageClient;
using Microsoft.Samples.ServiceHosting.AspProviders;
using Log = Microsoft.Samples.ServiceHosting.HelloFabric.ApplicationEnvironment;
using BlogEngine.Core.Azure.BlogProvider.Tables;

namespace BlogEngine.Core.Azure.BlogProvider
{
    public static class Setup
    {
        public static void CreateTables(StorageAccountInfo ai)
        {
            var ts = TableStorage.Create(ai);
            Log.LogInformation("Delete existing tables");
            bool deletedTables = false;
            try
            {
                var existingTables = ts.ListTables();
                foreach (var table in existingTables)
                {
                    deletedTables = true;
                    Log.LogInformation("Deleting table: " + table);
                    ts.DeleteTable(table);
                }
            }
            catch (System.Exception ex)
            {
                Log.LogError("ERROR: Could not access the tables! Check your settings and internet connection.\n\n" + ex);
                throw;
            }

            if (deletedTables)
            {
                Log.LogInformation("Sleep for 1 minute; waiting for the tables to be deleted.");
                System.Threading.Thread.Sleep(60000);
            }

            Log.LogInformation("Create tables");
            TableStorage.CreateTablesFromModel(typeof(RoleDataServiceContext), ai);
            TableStorage.CreateTablesFromModel(typeof(MembershipDataServiceContext), ai);

            TableStorage.CreateTablesFromModel(typeof(BlogDataServiceContext), ai);

            var createdTables = ts.ListTables();
            foreach (var table in createdTables)
                Log.LogInformation("Created table: " + table);
        }

        public static void FillTables(StorageAccountInfo ai, string appName)
        {
            var dataProvider = new DataProvider(false, ai);

            {
                Log.LogInformation("Create Roles");
                var dataContext = new RoleDataServiceContext(ai);

                dataContext.AddObject("Roles", new RoleRow(appName, "Administrators", "admin"));
                dataContext.AddObject("Roles", new RoleRow(appName, "Administrators", ""));
                dataContext.AddObject("Roles", new RoleRow(appName, "Editors", ""));

                dataContext.SaveChanges();
                Log.LogInformation("Roles Uploaded");
            }


            {
                Log.LogInformation("Create Users");
                var dataContext = new MembershipDataServiceContext(ai);

                var admin = new MembershipRow(appName, "admin") { Password = "admin", IsApproved = true };
                dataContext.AddObject("Membership", admin); // TODO: Create it "normally" to have all the fields properly initialized => Use TableStorageMembershipProvider.CreateUser()

                dataContext.SaveChanges();
                Log.LogInformation("Users Uploaded");
            }


            {
                Log.LogInformation("Create PingServices");
                var services = new List<PingService>();

                var serviceUrls = new[]
                {
                    "http://rpc.technorati.com/rpc/ping", "http://rpc.pingomatic.com/rpc2",
                    "http://ping.feedburner.com", "http://www.bloglines.com/ping",
                    "http://services.newsgator.com/ngws/xmlrpcping.aspx", "http://api.my.yahoo.com/rpc2",
                    "http://blogsearch.google.com/ping/RPC2", "http://rpc.pingthesemanticweb.com/"
                };
                for (int i = 0; i < serviceUrls.Length; i++)
                    services.Add(new PingService { Url = serviceUrls[i] });

                dataProvider.InsertAllRows(services);
                Log.LogInformation("PingServices Uploaded");
            }


            {
                Log.LogInformation("Create StopWords");
                var stopWords = new List<StopWord>
                {
                    new StopWord {Value = "a"},
                    new StopWord {Value = "about"},
                    new StopWord {Value = "actually"},
                    new StopWord {Value = "add"},
                    new StopWord {Value = "after"},
                    new StopWord {Value = "all"},
                    new StopWord {Value = "almost"},
                    new StopWord {Value = "along"},
                    new StopWord {Value = "also"},
                    new StopWord {Value = "an"},
                    new StopWord {Value = "and"},
                    new StopWord {Value = "any"},
                    new StopWord {Value = "are"},
                    new StopWord {Value = "as"},
                    new StopWord {Value = "at"},
                    new StopWord {Value = "be"},
                    new StopWord {Value = "both"},
                    new StopWord {Value = "but"},
                    new StopWord {Value = "by"},
                    new StopWord {Value = "can"},
                    new StopWord {Value = "cannot"},
                    new StopWord {Value = "com"},
                    new StopWord {Value = "could"},
                    new StopWord {Value = "de"},
                    new StopWord {Value = "do"},
                    new StopWord {Value = "down"},
                    new StopWord {Value = "each"},
                    new StopWord {Value = "either"},
                    new StopWord {Value = "en"},
                    new StopWord {Value = "for"},
                    new StopWord {Value = "from"},
                    new StopWord {Value = "good"},
                    new StopWord {Value = "has"},
                    new StopWord {Value = "have"},
                    new StopWord {Value = "he"},
                    new StopWord {Value = "her"},
                    new StopWord {Value = "here"},
                    new StopWord {Value = "hers"},
                    new StopWord {Value = "his"},
                    new StopWord {Value = "how"},
                    new StopWord {Value = "i"},
                    new StopWord {Value = "if"},
                    new StopWord {Value = "in"},
                    new StopWord {Value = "into"},
                    new StopWord {Value = "is"},
                    new StopWord {Value = "it"},
                    new StopWord {Value = "its"},
                    new StopWord {Value = "just"},
                    new StopWord {Value = "la"},
                    new StopWord {Value = "like"},
                    new StopWord {Value = "long"},
                    new StopWord {Value = "make"},
                    new StopWord {Value = "me"},
                    new StopWord {Value = "more"},
                    new StopWord {Value = "much"},
                    new StopWord {Value = "my"},
                    new StopWord {Value = "need"},
                    new StopWord {Value = "new"},
                    new StopWord {Value = "now"},
                    new StopWord {Value = "of"},
                    new StopWord {Value = "off"},
                    new StopWord {Value = "on"},
                    new StopWord {Value = "once"},
                    new StopWord {Value = "one"},
                    new StopWord {Value = "ones"},
                    new StopWord {Value = "only"},
                    new StopWord {Value = "or"},
                    new StopWord {Value = "our"},
                    new StopWord {Value = "out"},
                    new StopWord {Value = "over"},
                    new StopWord {Value = "own"},
                    new StopWord {Value = "really"},
                    new StopWord {Value = "right"},
                    new StopWord {Value = "same"},
                    new StopWord {Value = "see"},
                    new StopWord {Value = "she"},
                    new StopWord {Value = "so"},
                    new StopWord {Value = "some"},
                    new StopWord {Value = "such"},
                    new StopWord {Value = "take"},
                    new StopWord {Value = "takes"},
                    new StopWord {Value = "that"},
                    new StopWord {Value = "the"},
                    new StopWord {Value = "their"},
                    new StopWord {Value = "these"},
                    new StopWord {Value = "thing"},
                    new StopWord {Value = "this"},
                    new StopWord {Value = "to"},
                    new StopWord {Value = "too"},
                    new StopWord {Value = "took"},
                    new StopWord {Value = "und"},
                    new StopWord {Value = "up"},
                    new StopWord {Value = "use"},
                    new StopWord {Value = "used"},
                    new StopWord {Value = "using"},
                    new StopWord {Value = "very"},
                    new StopWord {Value = "was"},
                    new StopWord {Value = "we"},
                    new StopWord {Value = "well"},
                    new StopWord {Value = "what"},
                    new StopWord {Value = "when"},
                    new StopWord {Value = "where"},
                    new StopWord {Value = "who"},
                    new StopWord {Value = "will"},
                    new StopWord {Value = "with"},
                    new StopWord {Value = "www"},
                    new StopWord {Value = "you"},
                    new StopWord {Value = "your"}
                };

                Log.LogInformation("Saving StopWords");
                dataProvider.InsertAllRows(stopWords);
                Log.LogInformation("StopWords Uploaded");
            }


            {
                Log.LogInformation("Create Categories");

                var general = new Tables.Category
                {
                    Title = "General",
                    Description = "General",
                };
                dataProvider.InsertRow(general);
                Log.LogInformation("Categories Uploaded");
            }


            {
                Log.LogInformation("Create Posts");

                var firstPost = new Tables.Post
                {
                    Title = "Welcome to BlogEngine.NET 1.5 using Microsoft Azure",
                    Description = "The description is used as the meta description as well as shown in the related posts. It is recommended that you write a description, but not mandatory",
                    Content = @"<h2>Installation Completed!</h2>
<p>If you see this post it means that BlogEngine.NET 1.5 is running with Microsoft Azure and the AzureBlogProvider is configured correctly.</p>
<h2>Setup</h2>
<p>Find the sign-in link located either at the bottom or top of the page depending on your current theme and click it.
Now enter 'admin' in both the username and password fields and click the button. You will now see an admin menu appear.
It has a link to the 'Users' admin page. From there you can change the username and password.</p>",
                    Author = "admin",
                    IsPublished = true,
                    IsCommentsEnabled = true,
                };
                dataProvider.InsertRow(firstPost);
                Log.LogInformation("Posts Uploaded");
            }


            {
                Log.LogInformation("Create DataStoreSettings");

                var dataStore = new DataStoreSetting
                {
                    ExtensionType = 1,
                    ExtensionId = "be_WIDGET_ZONE",
                    Setting = @"<?xml version=""1.0"" encoding=""utf-16""?>
<WidgetData xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
  <Settings>&lt;widgets&gt;&lt;widget id=""d9ada63d-3462-4c72-908e-9d35f0acce40"" title=""TextBox""
    showTitle=""True""&gt;TextBox&lt;/widget&gt;&lt;widget id=""19baa5f6-49d4-4828-8f7f-018535c35f94"" title=""Administration""
    showTitle=""True""&gt;Administration&lt;/widget&gt;&lt;widget id=""d81c5ae3-e57e-4374-a539-5cdee45e639f"" title=""Search""
    showTitle=""True""&gt;Search&lt;/widget&gt;&lt;widget id=""77142800-6dff-4016-99ca-69b5c5ebac93"" title=""Tag cloud""
    showTitle=""True""&gt;Tag cloud&lt;/widget&gt;&lt;widget id=""4ce68ae7-c0c8-4bf8-b50f-a67b582b0d2e"" title=""RecentPosts""
    showTitle=""True""&gt;RecentPosts&lt;/widget&gt;&lt;/widgets&gt;
  </Settings>
</WidgetData>"
                };
                dataProvider.InsertRow(dataStore);
                Log.LogInformation("DataStoreSettings Uploaded");
            }


            {
                Log.LogInformation("Create Settings");
                var settings = new List<Setting>
                {
                    new Setting {Name = "administratorrole", Value = "Administrators"},
                    new Setting {Name = "alternatefeedurl", Value = ""},
                    new Setting {Name = "authorname", Value = "My name"},
                    new Setting {Name = "avatar", Value = "combine"},
                    new Setting {Name = "blogrollmaxlength", Value = "23"},
                    new Setting {Name = "blogrollupdateminutes", Value = "60"},
                    new Setting {Name = "blogrollvisibleposts", Value = "3"},
                    new Setting {Name = "contactformmessage", Value = "<p>I will answer the mail as soon as I can.</p>"},
                    new Setting {Name = "contactthankmessage", Value = "<h1>Thank you</h1><p>The message was sent.</p>"},
                    new Setting {Name = "culture", Value = "Auto"},
                    new Setting {Name = "dayscommentsareenabled", Value = "0"},
                    new Setting {Name = "description", Value = "Short description of the blog"},
                    new Setting {Name = "displaycommentsonrecentposts", Value = "True"},
                    new Setting {Name = "displayratingsonrecentposts", Value = "True"},
                    new Setting {Name = "email", Value = "user@example.com"},
                    new Setting {Name = "emailsubjectprefix", Value = "Weblog"},
                    new Setting {Name = "enablecommentsearch", Value = "True"},
                    new Setting {Name = "enablecommentsmoderation", Value = "False"},
                    new Setting {Name = "enablecontactattachments", Value = "True"},
                    new Setting {Name = "enablecountryincomments", Value = "True"},
                    new Setting {Name = "enablehttpcompression", Value = "True"},
                    new Setting {Name = "enableopensearch", Value = "True"},
                    new Setting {Name = "enablepingbackreceive", Value = "True"},
                    new Setting {Name = "enablepingbacksend", Value = "True"},
                    new Setting {Name = "enablerating", Value = "True"},
                    new Setting {Name = "enablereferrertracking", Value = "False"},
                    new Setting {Name = "enablerelatedposts", Value = "True"},
                    new Setting {Name = "enablessl", Value = "False"},
                    new Setting {Name = "enabletrackbackreceive", Value = "True"},
                    new Setting {Name = "enabletrackbacksend", Value = "True"},
                    new Setting {Name = "endorsement", Value = "http://www.dotnetblogengine.net/syndication.axd"},
                    new Setting {Name = "fileextension", Value = ".aspx"},
                    new Setting {Name = "geocodinglatitude", Value = "0"},
                    new Setting {Name = "geocodinglongitude", Value = "0"},
                    new Setting {Name = "handlewwwsubdomain", Value = ""},
                    new Setting {Name = "iscocommentenabled", Value = "False"},
                    new Setting {Name = "iscommentsenabled", Value = "True"},
                    new Setting {Name = "language", Value = "en-US"},
                    new Setting {Name = "mobiletheme", Value = "Mobile"},
                    new Setting {Name = "name", Value = "Name of the blog"},
                    new Setting {Name = "numberofrecentcomments", Value = "10"},
                    new Setting {Name = "numberofrecentposts", Value = "10"},
                    new Setting {Name = "postsperfeed", Value = "10"},
                    new Setting {Name = "postsperpage", Value = "10"},
                    new Setting {Name = "removewhitespaceinstylesheets", Value = "True"},
                    new Setting {Name = "searchbuttontext", Value = "Search"},
                    new Setting {Name = "searchcommentlabeltext", Value = "Include comments in search"},
                    new Setting {Name = "searchdefaulttext", Value = "Enter search term"},
                    new Setting {Name = "sendmailoncomment", Value = "True"},
                    new Setting {Name = "showdescriptioninpostlist", Value = "False"},
                    new Setting {Name = "showlivepreview", Value = "True"},
                    new Setting {Name = "showpostnavigation", Value = "True"},
                    new Setting {Name = "smtppassword", Value = "password"},
                    new Setting {Name = "smtpserver", Value = "mail.example.dk"},
                    new Setting {Name = "smtpserverport", Value = "25"},
                    new Setting {Name = "smtpusername", Value = "user@example.com"},
                    new Setting {Name = "storagelocation", Value = "~/App_Data/"},
                    new Setting {Name = "syndicationformat", Value = "Rss"},
                    new Setting {Name = "theme", Value = "Standard"},
                    new Setting {Name = "timestamppostlinks", Value = "True"},
                    new Setting {Name = "timezone", Value = "-5"},
                    new Setting {Name = "trackingscript", Value = ""}
                };

                dataProvider.InsertAllRows(settings);
                Log.LogInformation("Settings Uploaded");
            }
        }
    }
}